package com.mathassistant.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.mathassistant.client.event.ToAdminViewEvent;
import com.mathassistant.client.service.MyUserServiceAsync;
import com.mathassistant.shared.UserDTO;

public class LoginPresenter implements Presenter {
	
	public interface Display{
		HasClickHandlers getLoginButton();
		HasClickHandlers getCancelButton();
		HasValue<String> getUsernameTextbox();
		HasValue<String> getPasswordTextbox();
		Widget asWidget();
		void setWarning(String line1,String line2);
		void hideDialog();
		void showDialog();
	}
	
	private final Display display;
	private final SimpleEventBus eventBus;
	private final MyUserServiceAsync rpcService;
	private UserDTO user;
	
	public LoginPresenter(MyUserServiceAsync rpcService, SimpleEventBus eventBus, Display view){
		this.display = view;
		this.eventBus = eventBus;
		this.rpcService = rpcService;
		bind();
	}
	
	private void bind() {
		// TODO Auto-generated method stub
		this.display.getLoginButton().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				doLogin();
			}
		});
		this.display.getCancelButton().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				display.hideDialog();
			}
		});
	}

	protected void doLogin() {
		// TODO Auto-generated method stub
		user = new UserDTO();
		user.setName(display.getUsernameTextbox().getValue());
		user.setPassword(display.getPasswordTextbox().getValue());
		rpcService.Login(user, new AsyncCallback<UserDTO>() {
			
			@Override
			public void onSuccess(UserDTO result) {
				// TODO Auto-generated method stub
				// Login thành công
				if(result != null){
					eventBus.fireEvent(new ToAdminViewEvent(result));					
					display.hideDialog();
				}
				else{
					display.setWarning("\"H\u00E3y li\u00EAn h\u1EC7 v\u1EDBi admin qua email klnhb01@gmail.com",
							"N\u1EBFu b\u1EA1n kh\u00F4ng \u0111\u0103ng nh\u1EADp \u0111\u01B0\u1EE3c !!!\"");
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("LoginPresenter: Error loginning...");
			}
		});
	}

	@Override
	public void go(HasWidgets container) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void go() {
		// TODO Auto-generated method stub
	
	}

}
